package com.etop.weiway.wxmanage.interceptor;

import com.etop.weiway.commons.annotation.AccountRequired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * 用于检查当前用户有没有设置公众号
 * Created by KyLeo on 2015/1/29.
 */
public class AccountRequiredInterceptor extends HandlerInterceptorAdapter {
    /**
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o                   方法对象
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if (!(o instanceof DefaultServletHttpRequestHandler)) {
            HandlerMethod handlerMethod = (HandlerMethod) o;
            Method method = handlerMethod.getMethod();
            AccountRequired annotation = method.getAnnotation(AccountRequired.class);
            if (annotation != null) {
                HttpSession session = httpServletRequest.getSession();
                String strFullUrl = httpServletRequest.getRequestURL().toString();
                //todo this sentence may be wrong  by jeremie
                int funcIndex = strFullUrl.indexOf("/wxmanager");
                String url = strFullUrl.replace(strFullUrl.substring(funcIndex), "");
                if (session.getAttribute("currentAccoutId") == null) {
                    httpServletResponse.sendRedirect(url + "/wxmanager/account/list?info=message");
                    return false;
                }
            }
        }
        return true;
    }
}
